package best.driver.android.Utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.*;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.igexin.getuiext.util.BsPatchUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import best.driver.android.R;
import best.driver.android.BestApp;
import com.nostra13.universalimageloader.utils.L;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

public class Util {

    private static MediaPlayer sMediaPlayer;

        /** 排序 并 MD5 */
        public static String toSortMD5(Hashtable<String, Object> values) {
            StringBuilder buffer = new StringBuilder();
            ArrayList<String> keys = new ArrayList<String>(values.keySet());
            Collections.sort(keys);

            for (int i = 0, as = keys.size(); i < as; i++) {
                String key = keys.get(i);
                buffer.append(key).append(values.get(key));
            }
            buffer.append("EqYKiaWy6qBRvX0EUoUXC6O3xEeRhz");
            return MD5.md5(buffer.toString());
        }
	
	/**
     * 显示软键盘
     * 
     * @param context
     * @param edit
     */
    public static void showKeyboard(Context context, EditText edit) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(edit, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    
    /**
     * 隐藏软键盘
     * 
     * @param context
     */
    public static void hideKeyboard(Activity context) {
        InputMethodManager localInputMethodManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        View currentFocus = context.getCurrentFocus();
        if (currentFocus != null) {
            IBinder localIBinder = currentFocus.getWindowToken();
            if (localIBinder != null) {
                localInputMethodManager
                        .hideSoftInputFromWindow(localIBinder, 0);
            }
        }
    }

    public static Bitmap convertHeadPicture(Bitmap bitmap) {

        final float scale = BestApp.getInstance().getResources().getDisplayMetrics().density;
        int strokSize = (int) (4 * scale + 0.5f);

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Bitmap output = Bitmap.createBitmap(w, w, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();

        int y = (h - w) / 2 - 8;
        if (y < 0) {
            y = 0;
        }
        final Rect srcRect = new Rect(0, y, w, y + w);
        final Rect destRect = new Rect(0, 0, w, w);
        final RectF destRectF = new RectF(destRect);
        final float roundPx = w / 2;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(destRectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, srcRect, destRect, paint);

        paint.setARGB(255, 0xaa, 0xaa, 0xaa);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(strokSize);
        canvas.drawCircle(roundPx, roundPx, destRectF.width() / 2, paint);
        canvas.drawArc(destRectF, 0, 360, false, paint);

        return output;
    }

    public static Bitmap convertCornerPicture(Bitmap bitmap) {

        final float scale = BestApp.getInstance().getResources().getDisplayMetrics().density;
        int strokSize = (int) (2 * scale + 0.5f);

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Bitmap output = Bitmap.createBitmap(w, w, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();

        int y = (h - w) / 2 - 8;
        if (y < 0) {
            y = 0;
        }
        final Rect srcRect = new Rect(0, y, w, y + w);
        final Rect destRect = new Rect(0, 0, w, w);
        final RectF destRectF = new RectF(destRect);
        final float roundPx = 4 * scale;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(destRectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, srcRect, destRect, paint);

//        paint.setARGB(255, 0x33, 0x30, 0x3c);
//        paint.setStyle(Paint.Style.STROKE);
//        paint.setStrokeWidth(strokSize);
////        canvas.drawCircle(roundPx, roundPx, destRectF.width() / 2, paint);
//        canvas.drawArc(destRectF, 0, 360, false, paint);

        return output;
    }
    
    public static void showImageBitmap(final String uri,final ImageView view, DisplayImageOptions options) {
        if(options == null) {
            options = BestApp.options;
        }
		ImageLoaderUtil.getImageLoader().loadImage(uri, options,
		        new ImageLoaderUtilListener() {
		            @Override
		            public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap) {
		                if (bitmap != null) {
                                view.setImageBitmap(Util.convertHeadPicture(bitmap));
		                }
		            }

		            @Override
		            public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
                        //Toast.makeText(EDJApp.getInstance().getApplicationContext(), "kaofuckcao", Toast.LENGTH_SHORT).show();
		            }
		        });
	}

    public static void showBigImageBitmap(final String uri,final ImageView view) {
        ImageLoaderUtil.getImageLoader().loadImage(uri,
                new ImageLoaderUtilListener() {
                    @Override
                    public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap) {
                        if (bitmap != null) {
                            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            view.setImageBitmap(bitmap);
                        }
                    }
                    @Override
                    public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
                    }
                });
    }

    public static void showBigWithCornerBitmap(final String uri,final ImageView view) {
        ImageLoaderUtil.getImageLoader().loadImage(uri,
                new ImageLoaderUtilListener() {
                    @Override
                    public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap) {
                        if (bitmap != null) {
                            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            view.setImageBitmap(Util.convertCornerPicture(bitmap));
                            view.setTag(bitmap);
                        }
                    }
                    @Override
                    public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
                    }
                });
    }

    public static void showHeadImage(ImageView imageView, TextView tx_name, String avatar, String name) {
        if (!TextUtils.isEmpty(avatar)) {
            Util.showImageBitmap(avatar, imageView, null);
        } else {
            if (!TextUtils.isEmpty(name)) {
                String s = name.substring(0, 1);
                tx_name.setText(s);
                imageView.setImageResource(R.drawable.icon_app);
            }
        }
    }


    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    //bitmap转byte[]
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        try {
            int i;
            int j;
            if (bmp.getHeight() > bmp.getWidth()) {
                i = bmp.getWidth();
                j = bmp.getWidth();
            } else {
                i = bmp.getHeight();
                j = bmp.getHeight();
            }

            Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
            Canvas localCanvas = new Canvas(localBitmap);

            localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i, j), null);
            if (needRecycle) {
                bmp.recycle();
            }
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100, localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();

            localByteArrayOutputStream.close();
            return arrayOfByte;
        } catch (Exception e) {
            return null;
        }
    }
    public static String getDistanceStr(double distance) {
        if(distance < 900) {
            int temp = (int)distance + 100;
            return temp/100 *100 +"米以内";
        }
        int temp = (int) distance + 1000;
        return temp/1000 +"公里以内";
    }

    public static String getOnePointNumber(double num) {
        DecimalFormat df = new DecimalFormat("0.0");
        String str = df.format(num);
        return str;
    }

    private static boolean playSound(final int streamType, final Uri uri, Boolean loop) {
            try {
                L.d("playSound.1 try to play sound:%s", uri);
                if (uri == null) {
                    return false;
                }

                if (sMediaPlayer != null) {
                    try {
                        if (sMediaPlayer.isPlaying()) {
                            sMediaPlayer.stop();
                        }
                    } catch (Exception e) {
                        L.d("playSound.2 e:%s", e.toString());
                        e.printStackTrace();
                    }

                    try {
                        sMediaPlayer.reset();
                        sMediaPlayer.release();
                        sMediaPlayer = null;
                    } catch (Exception e) {
                        L.d("playSound.3 e:%s", e.toString());
                        e.printStackTrace();
                    }
                }

                sMediaPlayer = new MediaPlayer();
                final AudioManager audioManager = (AudioManager) BestApp.getInstance()
                        .getSystemService(
                                Context.AUDIO_SERVICE);
                final int volume = audioManager.getStreamVolume(streamType);
                L.d("playSound.4 save audio vol = " + volume);
                audioManager.setStreamVolume(streamType, audioManager.getStreamMaxVolume(streamType), 0);
                //sStreamType = streamType;

                sMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        mp.release();
                        sMediaPlayer = null;
                        audioManager.setStreamVolume(streamType, volume, 0);
                    }
                });
                sMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        mp.release();
                        sMediaPlayer = null;
                        L.e("playSound.5 Error in MediaPlayer: (" + what + ") with extra (" + extra + ")");
                        audioManager.setStreamVolume(streamType, volume, 0);
                        return false;
                    }
                });
                sMediaPlayer.setAudioStreamType(streamType);
                sMediaPlayer.setLooping(loop);
                try {
                    sMediaPlayer.setDataSource(BestApp.getInstance(), uri);
                } catch (Exception e) {
                    L.d("playSound.6 e:%s", e.toString());
                    e.printStackTrace();
                    return false;
                }
                try {
                    sMediaPlayer.prepare();
                } catch (Exception e) {
                    L.d("playSound.7 e:%s", e.toString());
                    e.printStackTrace();
                    return false;
                }
                sMediaPlayer.start();
                return true;
            } catch (IllegalStateException e) {
                L.d("playSound.8 e:%s", e.toString());
                e.printStackTrace();
            }
        return false;
}


}
